package com.sky.controller.admin;

import com.sky.constant.MessageConstant;
import com.sky.result.Result;
import com.sky.utils.AliOssUtil;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/admin/common/upload")
@Api(tags = "通用接口")
@Slf4j
public class CommonController {
    @Autowired
    private AliOssUtil aliOssUtil;
    @PostMapping
    public Result<String> upload(MultipartFile file) {
        log.info("文件上传:{}", file);
        //这里不能使用原始文件名而是使用UUID
        //首先要拿到原始文件的原始后缀
        try {
            String originalFilename = file.getOriginalFilename();
            //截取原始文件名的后缀
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            //使用UUID生成文件名
            String newName = UUID.randomUUID().toString() + suffix;
            //调用工具类的上传文件的方法
            //返回值是文件的访问路径
            String newPath = aliOssUtil.upload(file.getBytes(), newName);
            return Result.success(newPath);
        } catch (IOException e) {
            log.error(MessageConstant.UPLOAD_FAILED);
        }
        return null;

    }
}
